<template>
	<div>
		<!-- 面包屑导航区域 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>系统管理</el-breadcrumb-item>
			<el-breadcrumb-item>员工管理</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片视图区域 -->
		<el-card class="box-card">
			<!-- 搜索与添加区域 -->
			<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
				<el-form-item label="姓名:">
					<el-input v-model="queryInfo.LoginName"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-select v-model="queryInfo.IsLockout" placeholder="请选择">
						<el-option label="全部" value=""></el-option>
						<el-option label="锁定" value="是"></el-option>
						<el-option label="未锁定" value="否"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onSubmit" icon="el-icon-search" plain>查询</el-button>
				</el-form-item>
				<div>
					<el-form-item>
						<el-button type="warning" round @click="addDialogVisible=true" icon="el-icon-circle-plus-outline" plain>添加用户</el-button>
					</el-form-item>
				</div>

			</el-form>
			<!-- 用户列表区域 -->
			<el-table :data="userlist" border stripe>
				<el-table-column label="编号" prop="Id" width="50px"></el-table-column>
				<el-table-column label="登录名" prop="LoginName" width="100px"></el-table-column>
				<el-table-column label="邮箱" prop="ProtectEmail"></el-table-column>
				<el-table-column label="手机号" prop="ProtectMTel"></el-table-column>
				<el-table-column label="创建时间" prop="CreateTime"></el-table-column>
				<el-table-column label="是否锁定" width="70px">
					<template slot-scope="scope">
						<el-switch v-model="scope.row.IsLockout=='是'" @change="userStateChanged(scope.row)">
						</el-switch>
					</template>
				</el-table-column>
				<el-table-column label="锁定时间" prop="LockTime"></el-table-column>
				<el-table-column label="操作" width="350px">
					<template slot-scope="scope">
						<!-- 分配角色按钮 -->
						<el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)" plain>角色</el-button>
						<!-- 修改按钮 -->
						<el-button type="success" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)" plain>修改</el-button>
						<!-- 删除按钮 -->
						<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.Id)" plain>删除</el-button>
						<!-- 修改按钮 -->
						<el-button type="primary" icon="el-icon-s-opportunity" size="mini" @click="resetDialog(scope.row)" plain>重置</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页区域 -->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum"
			 :page-sizes="[5, 10, 15, 20]" :page-size="queryInfo.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</el-card>
		<!-- 添加用户的对话框 -->
		<el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
			<!-- 内容主体区域 -->
			<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
				<el-form-item label="用户名" prop="LoginName">
					<el-input v-model="addForm.LoginName"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="Password">
					<el-input type="password" v-model="addForm.Password" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="确认密码" prop="RefPassword">
					<el-input type="password" v-model="addForm.RefPassword" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="ProtectEmail">
					<el-input v-model="addForm.ProtectEmail"></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="ProtectMTel">
					<el-input v-model="addForm.ProtectMTel"></el-input>
				</el-form-item>
			</el-form>
			<!-- 底部区域 -->
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addUser">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 修改用户的对话框 -->
		<el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
			<el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
				<el-form-item label="用户名" prop="Password">
					<el-input v-model="editForm.LoginName" disabled></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="ProtectEmail">
					<el-input v-model="editForm.ProtectEmail"></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="ProtectMTel">
					<el-input v-model="editForm.ProtectMTel"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editUserInfo">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 分配角色的对话框 -->
		<el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
			<div>
				<p>当前的用户:{{userInfo.LoginName}}</p>
				<!--  <p>当前的角色:{{userInfo.role_name}}</p> -->
				<p>分配角色:
					<el-transfer @change="changde" v-model="value" :titles="title" :props="{
				          key: 'Id',
				          label: 'Name'
				        }"
					 :data="rolesList">
					</el-transfer>
				</p>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="setRoleDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="saveRoleInfo">确 定</el-button>
			</span>
		</el-dialog>

	</div>
</template>

<script>
	export default {
		data() {
			//验证邮箱的规则
			var checkEmail = (rule, value, cb) => {
				//验证邮箱的正则表达式
				const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
				if (regEmail.test(value)) {
					//合法的邮箱
					return cb()
				}
				cb(new Error('请输入合法的邮箱'))
			}
			//验证手机号规则
			var checkMobile = (rule, value, cb) => {
				const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

				if (regMobile.test(value)) {
					//合法的手机号
					return cb()
				}
				cb(new Error('请输入合法的手机号'))
			}
			//确认密码
			var checkPassword = (rule, value, cb) => {
				if (this.addForm.Password == value) {
					//合法的邮箱
					return cb()
				}
				cb(new Error('两次密码不一致'))
			}
			return {
				//获取用户列表的参数对象
				queryInfo: {
					LoginName: '',
					IsLockout: '',
					//当前的页数
					page: 1,
					//当前每页显示多少条数据
					limit: 5
				},
				RefPassword: '',
				userlist: [],
				total: 0,
				//控制添加用户对话框的显示与隐藏
				addDialogVisible: false,
				// 添加用户的表单数据
				addForm: {
					RefPassword: '',
					LoginName: '',
					Password: '',
					ProtectEmail: '',
					ProtectMTel: ''
				},
				//添加表单的验证规则对象
				addFormRules: {
					LoginName: [{
							required: true,
							message: '请输入用户名',
							tigger: 'blur'
						},
						{
							min: 3,
							max: 10,
							message: '用户名的长度在3~10个字符之间',
							tigger: 'blur',
						}
					],
					Password: [{
							required: true,
							message: '请输入密码',
							tigger: 'blur'
						},
						{
							min: 6,
							max: 15,
							message: '用户名的长度在6~15个字符之间',
							tigger: 'blur',
						}
					],
					ProtectEmail: [{
							required: true,
							message: '请输入邮箱',
							tigger: 'blur'
						},
						{
							validator: checkEmail,
							tigger: 'blur'
						}
					],
					ProtectMTel: [{
							required: true,
							message: '请输入手机号',
							tigger: 'blur'
						},
						{
							validator: checkMobile,
							tigger: 'blur'
						}
					],
					RefPassword: [{
							required: true,
							message: '请输入密码',
							tigger: 'blur'
						},
						{
							min: 6,
							max: 15,
							message: '用户名的长度在6~15个字符之间',
							tigger: 'blur',
						},
						{
							validator: checkPassword,
							tigger: 'blur'
						}
					]
				},
				//控制修改用户对话框的显示与隐藏
				editDialogVisible: false,
				//查询到用户信息对象
				editForm: {},
				//删除对象
				DeteteForm: {},
				//修改表单的验证规则对象
				editFormRules: {
					email: [{
							required: true,
							message: '请输入邮箱',
							tigger: 'blur'
						},
						{
							validator: checkEmail,
							tigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							message: '请输入手机号',
							tigger: 'blur'
						},
						{
							validator: checkMobile,
							tigger: 'blur'
						}
					]
				},
				//控制分配角色对话框的显示与隐藏
				setRoleDialogVisible: false,
				//需要被分配角色的用户信息
				userInfo: {},
				//所有角色的数据列表
				rolesList: [],
				//已选中的角色Id值
				value: [],
				title: ["系统所有角色", "当前用户的角色"],
				resetInfo: 0
			}
		},
		created() {
			this.getUserList()
		},
		methods: {
			changde() {
				console.log(this.value)
			},
			//多条件搜索
			onSubmit() {
				this.getUserList();
			},
			async getUserList() {
				const {
					data: res
				} = await this.$http.get('api/Staff/GetStaffList', {
					params: {
						LoginName: this.queryInfo.LoginName,
						IsLockout: this.queryInfo.IsLockout,
						page: this.queryInfo.page,
						limit: this.queryInfo.limit
					}
				})
				if (res.status !== 200) {
					return this.$message.error('获取用户列表失败！')
				}
				this.userlist = res.data
				this.total = res.total
				console.log(res)
			},
			//监听 pagesize 改变的事件
			handleSizeChange(newSize) {
				//console.log(newSize)
				this.queryInfo.limit = newSize
				this.getUserList()
			},
			//监听 页码值 改变的事件
			handleCurrentChange(newPage) {
				//console.log(newPage)
				this.queryInfo.page = newPage
				this.getUserList()
			},
			//监听 switch 开关状态的改变
			async userStateChanged(userinfo) {
				console.log(userinfo)
				const {
					data: res
				} = await this.$http.post(
					'api/Staff/UpdateLock', {
						LoginName: userinfo.LoginName
					}
				)
				if (res.code !== 0) {
					//userinfo.mg_state = !userinfo.mg_state
					return this.$message.error(res.msg)
				}
				this.$message.success(res.msg)
				this.getUserList();
			},
			//监听添加用户对话框的关闭事件
			addDialogClosed() {
				this.$refs.addFormRef.resetFields()
			},
			//点击按钮，添加新用户
			addUser() {
				this.$refs.addFormRef.validate(async valid => {
					//console.log(valid)
					if (!valid) return
					//可以发起添加用户的网络请求
					const {
						data: res
					} = await this.$http.post('api/Staff/AddUser', this.addForm)
					if (res.code == 0) {
						this.$message.success('添加用户成功！')
						//隐藏添加用户的对话框
						this.addDialogVisible = false
						//重新获取用户列表数据
						this.getUserList()
					} else {
						this.$message.error(res.msg)
					}

				})
			},
			//展示编辑用户的对话框
			async showEditDialog(row) {
				this.editForm = row
				this.editDialogVisible = true
			},
			//监听修改用户对话框的关闭事件
			editDialogClosed() {
				this.$refs.editFormRef.resetFields()
			},
			//修改用户信息并提交
			editUserInfo() {
				this.$refs.editFormRef.validate(async valid => {
					//console.log(valid)
					if (!valid) return
					//可以发起修改用户的网络请求
					const {
						data: res
					} = await this.$http.post('api/Staff/GetEdit', this.editForm)
					if (res.code !== 0) {
						this.$message.error('更新用户信息失败！')
					}
					//关闭对话框
					this.editDialogVisible = false
					//刷新数据列表
					this.getUserList()
					//提示修改成功
					this.$message.success('更新用户信息成功！')
				})
			},
			//根据Id删除对应的用户信息
			async removeUserById(Id) {
				this.DeteteForm.Id = Id;
				//弹框询问用户是否删除数据
				const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err)
				//如果用户确认删除，则返回值为字符串 confirm
				//如果用户取消了删除，则返回值为字符串 cancel
				//console.log(confirmResult)
				if (confirmResult !== 'confirm') {
					return this.$message.info('已取消删除')
				}
				//console.log('确认了删除')
				const {
					data: res
				} = await this.$http.post('api/Staff/Delete', this.DeteteForm)
				if (res.code != 0) {
					return this.$message.error('删除用户失败！')
				}
				this.$message.success('删除用户成功！')
				this.getUserList()
			},
			//展示分配角色的对话框
			async setRole(userInfo) {
				this.userInfo = userInfo
				//在展示对话框之前，获取所有角色的列表
				const {
					data: res
				} = await this.$http.get('api/Staff/GetAllRoles')
				if (res.code !== 0) {
					return this.$message.error('获取全部角色列表失败！')
				}
				this.rolesList = res.data;
				const {
					data: ress
				} = await this.$http.post('api/Staff/GetMyRoles', this.userInfo)
				if (res.code !== 0) {
					return this.$message.error('获取角色列表失败！')
				}
				this.value = ress.data;
				this.setRoleDialogVisible = true
			},
			//点击按钮 ，分配角色
			async saveRoleInfo() {
				const {
					data: res
				} = await this.$http.get('api/Staff/EditMR', {
					params: {
						Id: this.userInfo.Id,
						Value: this.value.toString()
					}
				})
				if (res.code !== 0) {
					return this.$message.error(res.msg)
				}
				this.$message.success(res.msg)
				this.getUserList();
				this.setRoleDialogVisible = false;
			},
			//监听分配角色对话框的关闭事件
			setRoleDialogClosed() {
				this.userInfo = {}
			},
			async resetDialog(row) {
				this.resetInfo = row;
				//弹框询问用户是否删除数据
				const confirmResult = await this.$confirm('此操作将重置该用户密码, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err)
				//如果用户确认删除，则返回值为字符串 confirm
				//如果用户取消了删除，则返回值为字符串 cancel
				//console.log(confirmResult)
				if (confirmResult !== 'confirm') {
					return this.$message.info('已取消重置')
				}
				//console.log('确认了删除')
				const {
					data: res
				} = await this.$http.post('api/Staff/ResetUser', this.resetInfo)
				if (res.code != 0) {
					return this.$message.error('重置用户密码失败！')
				}
				this.$message.success('重置用户密码成功！')
				this.getUserList()
			}
		}
	}
</script>

<style Lang="less">
</style>
